<template>
	<view class="bg-white">
		<view class="edgeInsetTop"></view>
		<view :class="'color' + formData.state" class="tips"
			v-if="formData.state === 0 || formData.state === 1 || formData.state === 2">
			{{msg}}
		</view>
		<view class="padding-lr">
			<form @submit="formSubmit">
				<view class="cu-form-group">
					<view class="title flex align-center"> <text class="margin-right-sm iconfont icon-xingming"></text>
						<text>姓名</text>
					</view>
					<input disabled placeholder="请输入姓名" maxlength="32"
						name="realname" v-model="formData.realname"></input>
				</view>
				<!-- <view class="cu-form-group">
					<view class="title flex align-center"> <text class="margin-right-sm iconfont icon-nianling"></text>
						<text>年龄</text>
					</view>
					<input :disabled="formData.state === 0 || formData.state === 1" type="number" maxlength="3"
						placeholder="请输入年龄" name="age" v-model="formData.age"></input>
				</view> -->
				<view class="cu-form-group">
					<view class="title flex align-center"> <text
							class="margin-right-sm iconfont icon-tijianxingbiefenxi"></text> <text>性别</text> </view>
					<view style="display: none;">
						<input name="sex" v-model="formData.sex" disabled></input>
					</view>
					<switch :disabled="formData.state === 0 || formData.state === 1" class='switch-sex' @change="Gender"
						:class="gender?'checked':''" :checked="gender?true:false">
					</switch>
				</view>
				<view class="cu-form-group">
					<view class="title flex align-center"> <text class="margin-right-sm iconfont icon-shouji"></text>
						<text>手机</text>
					</view>
					<input :disabled="formData.state === 0 || formData.state === 1" type="number" placeholder="请输入手机号码"
						maxlength="11" name="mobile" v-model="formData.mobile"></input>
				</view>
				<!-- <view class="cu-form-group" v-if="formData.state === -1 || formData.state === 2">
					<view class="title flex align-center"> <text class="margin-right-sm iconfont icon-yanzhengma1"></text>
						<text>验证码</text> </view>
					<input type="number" maxlength="6" placeholder="请输入验证码" name="code" v-model="formData.code"></input>
					<text class="text-green" v-if="!cTimer" @tap="resend">获取验证码</text>
					<template v-else>
						<text v-if="countdown == 0" @tap="resend">重新发送</text>
						<text v-if="countdown > 0" class="time">{{countdown}}秒后重新发送</text>
					</template>
				</view> -->
				<view class="cu-form-group">
					<view class="title flex align-center"> <text
							class="margin-right-sm iconfont icon-shenfenzhengrenzheng"></text> <text>身份证号</text> </view>
					<input disabled type="idcard" placeholder="请输入身份证号"
						name="idcard_no" maxlength="18" v-model="formData.idcard_no"></input>
				</view>


				<wanl-select :disabled="formData.state === 0 || formData.state === 1" :list="level" label-key="name"
					value-key="id" title="选择医护等级" v-model="medical_level" placeholder="请选择医护等级"
					@change="selectMedical_level" v-if="formData.type == 1">
					<view class="title flex align-center"> <text
							class="margin-right-sm iconfont icon-yishengshenhe"></text> <text>医护等级</text> </view>
				</wanl-select>
				
				<view class="cu-form-group" v-if="formData.type == 3">
					<view class="title flex align-center"> <text class="margin-right-sm iconfont icon-fuwuxiangmu"></text>
						<text>服务项目</text>
					</view>
					<view class="right flex justify-start align-center" @tap="showTree">
						<text class="text-cut" :class="{placeholder:!homekeep_text}">{{homekeep_text || '请选择服务项目'}}</text>
						<text class="wlIcon-fanhui2"></text>
					</view>
				</view>
				
				<view class="cu-form-group area">
					<view class="title flex align-center"> <text class="margin-right-sm iconfont icon-chengshijiexi"></text>
						<text>所在地区</text>
					</view>
					<view class="right flex justify-start align-center" @tap="open">
						<text class="text-cut" :class="{placeholder:!formatted_address}">{{formatted_address || '选择地区'}}</text>
						<text class="wlIcon-fanhui2"></text>
					</view>
					
				</view>
				<view class="cu-form-group flex flex-direction" style="align-items: flex-start;">
					<view class="title flex align-center" style="height: 100rpx;"> <text
							class="margin-right-sm iconfont icon-chengshijiexi"></text> <text>详细地址</text> </view>
					<view class="textarea">
						<textarea :disabled="formData.state === 0 || formData.state === 1" v-model="formData.address"
							placeholder="请输入详细地址" name="introduce" />
					</view>
				</view>
				<view class="cu-form-group flex flex-direction" style="align-items: flex-start;">
					<view class="title flex align-center" style="height: 100rpx;"> <text
							class="margin-right-sm iconfont icon-tuandui"></text> <text>自我介绍</text> </view>
					<view class="textarea">
						<textarea :disabled="formData.state === 0 || formData.state === 1" v-model="formData.introduce"
							placeholder="请输入自我介绍" name="introduce" />
					</view>
				</view>


				<view class="cu-form-group flex flex-direction" style="align-items: flex-start;">
					<view class="title flex align-center" style="height: 100rpx;"> <text
							class="margin-right-sm iconfont icon-ziyuan"></text> <text>身份证照片</text> </view>
					<view class="list flex justify-start align-center">
						<image @tap="previewImage([formData.idcard_front],0)" :src="$wanlshop.oss(formData.idcard_front)" mode="aspectFill" class="rightLeftImg item">
						</image>

						<image @tap="previewImage([formData.idcard_back],0)" :src="$wanlshop.oss(formData.idcard_back)" mode="aspectFill" class="rightLeftImg item">
						</image>
					</view>
				</view>

				<view class="cu-form-group flex flex-direction" style="align-items: flex-start;">
					<view class="title flex align-center" style="height: 100rpx;"> <text
							class="margin-right-sm iconfont icon-hetongguanli"></text> <text>其他相关证明文件照片</text> </view>
					<view class="list flex justify-start align-center flex-wrap" style="padding-bottom: 0;">
						<block v-if="certification.length > 0">
							<view v-for="(item,index) in certification" :key="index"
							class="item flex justify-center align-center margin-bottom-sm">
								<image :src="$wanlshop.oss(item)" mode="aspectFill" class="rightLeftImg" @tap="previewImage(certification,index)">
								</image>
								<view class="cu-tag bg-red" @tap.stop="close(index,'certification')" v-if="formData.state === -1 || formData.state === 2">
									<text class='wlIcon-shanchu2'></text>
								</view>
							</view>
						</block>
						<view v-if="formData.state === -1 || formData.state === 2"
							class="item flex justify-center align-center margin-bottom-sm">
							<image @click="chooseImg('certification')" :src="$wanlshop.oss('/uploads/staticImage/user/upload.jpg')" mode="widthFix"></image>
						</view>
					</view>
				</view>
				
				<view class="cu-form-group flex flex-direction" style="align-items: flex-start;">
					<view class="title flex align-center" style="height: 100rpx;"> <text
							class="margin-right-sm iconfont icon-hetongguanli"></text> <text>健康证</text> </view>
					<view class="list flex justify-start align-center flex-wrap" style="padding-bottom: 0;">
						<block v-if="health_image.length > 0">
							<view v-for="(item,index) in health_image" :key="index"
							class="item flex justify-center align-center margin-bottom-sm">
								<image :src="$wanlshop.oss(item)" mode="aspectFill" class="rightLeftImg" @tap="previewImage(health_image,index)">
								</image>
								<view class="cu-tag bg-red" @tap.stop="close(index,'health_image')" v-if="formData.state === -1 || formData.state === 2">
									<text class='wlIcon-shanchu2'></text>
								</view>
							</view>
						</block>
						<view v-if="formData.state === -1 || formData.state === 2"
							class="item flex justify-center align-center margin-bottom-sm">
							<image @click="chooseImg('health_image')" :src="$wanlshop.oss('/uploads/staticImage/user/upload.jpg')" mode="widthFix"></image>
						</view>
					</view>
				</view>
				
				<view class="xieyi" v-if="formData.state === -1 || formData.state === 2">
					<view class="radio flex justify-center align-center" @tap="!checked ? $wanlshop.msg('请先阅读服务协议并同意') : ''">
						<view class="radio text-x" v-if="checked">
							<text class="wlIcon-xuanze-danxuan wanl-gray-light mg20"></text>
						</view>
						<view class="radio text-x" v-else>
							<text class="wlIcon-xuanze wanl-gray-light mg20"></text>
						</view>
						<view class="margin-left-sm" style="line-height: 60rpx;">我已阅读并同意</view>
					</view>
					<view class="xieyi_content" style="margin-left: -10rpx;">
						<text @click="$wanlshop.to(`/pages/article/details?id=5&title=服务人员申请协议&type=singlepage&source=99`)">《服务人员申请协议》</text>
					</view>
				</view>

				<view class="padding-bj flex flex-direction" v-if="formData.state === -1 || formData.state === 2">
					<button form-type="submit"
						class="cu-btn bg-green margin-tb lg">{{formData.state == 2 ? '重新提交' : '提交'}}</button>
				</view>
			</form>
		</view>
		<wanl-tree :disabled="formData.state === 0 || formData.state === 1" ref="gqTree" :range="serves" title="选择服务项目" @confirm="treeConfirm"></wanl-tree>
		<wanl-select-address :provinvial="openLists" ref="wanlAddressRef" :address="address" @change="change" @close="close"></wanl-select-address>
	</view>
</template>

<script>
	import graceChecker from '@/common/graceChecker';
	import {
		mapState
	} from 'vuex';
	export default {
		computed: {
			...mapState(['user'])
		},
		data() {
			return {
				type:0,
				address: {
					province: {id:'',name:'',pid:''},
					city: {id:'',name:'',pid:''},
					area: {id:'',name:'',pid:''},
					street: {id:'',name:'',pid:''},
				},
				show: false,
				typeText: ['医护人员', '陪诊人员', '家政人员'],
				gender: true,
				certification: [],
				health_image: [],
				formData: {
					province:'',
					city: '', // 服务城市code
					district:'',
					street:'',
					address:'',
					lng:'',
					lat:'',
					
					state: -1, // （0：待审核；1：已通过；2：已拒绝）
					type: 0, // 职业类型（1：医护人员；2：陪诊人员；3：家政人员；4：司机；5：志愿者）
					realname: '', // 真实姓名
					sex: 1, // 性别（1：男；2：女）
					age: '', // 年龄
					idcard_no: '', // 身份证号码【限制18位】
					idcard_front: '', // 身份证正面照
					idcard_back: '', // 身份证反面照
					mobile: '', // 手机号
					introduce: '', // 自我介绍
					certification: '', // 其他相关证明文件照片（如：驾照，健康证，护理证等）
					health_image: '', // 健康证
					medical_level: '', // type为1时，申请的医护等级
					homekeep_ids: '', // type为3时，所具备的家政服务项目
					// code: '', // 手机验证码
				},
				formatted_address:'',
				level: [],
				serves: [],
				medical_level: '',
				homekeep_ids: [],
				homekeep_text: '',

				countdown: 60,
				cTimer: null,
				msg: '',
				temp: [],
				openLists:[],
				
				checked: false,
				flag: true,
			}
		},
		async onLoad(option) {
			this.formData.type = option.t
			this.type = option.t
			uni.setNavigationBarTitle({
				title: `申请${this.typeText[option.t - 1]}`
			})
			if (option.t == 1 || option.t == 3) {
				this.getdatadict()
			}
			this.getInfo(option)
			
			await uni.request({
				url: '/publics/city/getOpenLists',
				method: 'POST',
				success: res => {
					this.openLists = res.data;
				}
			});
		},
		methods: {
			close() {
				console.log(JSON.stringify(this.address))
				if(!this.flag) {
					this.$refs.wanlAddressRef.setData(this.address);
				}
			},
			open() {
				if (this.formData.state === 0 || this.formData.state === 1) {
					return false
				}
				this.$refs.wanlAddressRef.open()
			},
			change(value) {
				this.flag = false
				if(!value.street.name) return false;
				let address = `${value.province.name || ''}${value.city.name || ''}${value.area.name || ''}${value.street.name || ''}`;
				this.formatted_address = address;
				uni.request({
					url: '/member/address/getAddressLatlng',
					data: {
						key: this.$config.amapkey,
						address: address,
						city:value.city.name,
						output: 'JSON'
					},
					success: (res) => {
						this.flag = true
						let location = res.data[0].location.split(',');
						let lng = location[0];
						let lat = location[1];
						this.formData.province = value.province.id;
						this.formData.city = value.city.id;
						this.formData.district = value.area.id;
						this.formData.street = value.street.id;
						this.formData.lng = lng;
						this.formData.lat = lat;
						
						this.address = {
							province: {id:value.province.id,name:value.province.name,pid:0},
							city: {id:value.city.id,name:value.city.name,pid:value.province.id},
							area: {id:value.area.id,name:value.area.name,pid:value.city.id},
							street: {id:value.street.id,name:value.street.name,pid:value.area.id}
						}
						this.$refs.wanlAddressRef.setData(this.address);
					}
				})
			},
			async getInfo(option) {
				var _this = this;
				let data = await uni.request({url: '/wanlshop/User/verifiedInfo',method: 'POST'})
				let verifiedInfo = data[1].data
				await uni.request({
					url: '/Userapply/info',
					method: 'POST',
					data: {
						type: option.t
					},
					async success(res) {
						let datas = await uni.request({
							url: '/publics/category/lists',
							method: 'POST',
							data: {
								type: 'homeking'
							},
						});
						_this.serves = datas[1].data;
						if (res.data) {
							_this.formatted_address = `${res.data.city_name.province}${res.data.city_name.city}${res.data.city_name.district}${res.data.city_name.street}`;
							if(verifiedInfo.status == 1) {
								res.data.realname = verifiedInfo.truename
								res.data.idcard_no = verifiedInfo.idcard
								res.data.idcard_back = verifiedInfo.back_card_image
								res.data.idcard_front = verifiedInfo.front_card_image
							}
							_this.formData = Object.assign(_this.formData, res.data);
							res.data.state = Number(res.data.state)
							if (res.data.state === 0) {
								_this.msg = '您当前正在审核中,请耐心等待'
							} else if (res.data.state === 1) {
								_this.msg = '审核已通过'
							} else if (res.data.state === 2) {
								_this.msg = `审核未通过原因：${res.data.refuse_reason}`
							}
							_this.certification = res.data.certification.split(',')
							_this.health_image = res.data.health_image.split(',')
							if (option.t == 1) {
								_this.medical_level = res.data.medical_level;
							}
							if (option.t == 3) {
								_this.homekeep_ids = res.data.homekeep_ids;
								if(res.data.homekeep_ids.length > 0) {
									_this.homekeep_text = _this.findItemById(datas[1].data,res.data.homekeep_ids).join(',');
								}
							}
						} else {
							let users = _this.$store.state.user;
							if(users.infos) {
								_this.formatted_address = `${users.infos.address_detail}`;
								for (let i in users.infos) {
									for (let j in _this.formData) {
										if (i === j) {
											_this.formData[j] = users.infos[i];
										}
									}
								}
								_this.formData.state = -1;
								_this.formData.type = _this.type;
								console.log(_this.formData)
								let addresss = users.infos.address_detail.split('/');
								_this.address = {
									province: {id:users.infos.province,name:addresss[0],pid:0},
									city: {id:users.infos.city,name:addresss[1],pid:users.infos.province},
									area: {id:users.infos.district,name:addresss[2],pid:users.infos.city},
									street: {id:users.infos.street,name:addresss[3],pid:users.infos.district}
								}
							} else {
								_this.formData.realname = verifiedInfo.truename
								_this.formData.idcard_no = verifiedInfo.idcard
								_this.formData.idcard_back = verifiedInfo.back_card_image
								_this.formData.idcard_front = verifiedInfo.front_card_image
							}
						}
					}
				});
			},
			async getdatadict() {
				await uni.request({
					url: '/addons/medicalvisit/api.Common/getMedicalLevel',
					method: 'POST',
					data: {
						datadict_id: '3'
					},
					success: res => {
						let temp = []
						for (let var1 in res.data) {
							temp.push({
								id:var1,
								name:res.data[var1]
							})
						}
						this.level = temp;
					}
				});
			},
			selectMedical_level(d) {
				this.formData.medical_level = d.id;
			},
			Gender(e) {
				if (e.detail.value == true) {
					this.gender = true;
					this.formData.sex = 1
				} else {
					this.gender = false;
					this.formData.sex = 2
				}
			},
			formSubmit: function(e) {
				if (this.formData.state === 0 || this.formData.state === 1) {
					return this.$wanlshop.msg(this.msg)
				}
				if (!this.checked) {
					return this.$wanlshop.msg('请勾选服务人员申请协议');
				}
				//定义表单规则
				let formData = Object.assign({}, this.formData)
				formData.certification = this.certification.join(',');
				formData.health_image = this.health_image.join(',');
				console.log(formData)
				let rule = [
					{name: 'realname',checkType: 'string',checkRule: '2,32',errorMsg: '真实姓名，至少2-32字符'},
					// {name: 'age',checkType: 'notnull',errorMsg: '请输入年龄'},
					{name: 'mobile',checkType: 'phoneno',errorMsg: '请输入真实的手机号码'},
					// {name: 'code',checkType: 'notnull',errorMsg: '请输入手机验证码'},
					{name: 'idcard_no',checkType: 'string',checkRule: '18',errorMsg: '请输入18位的身份证号码'},
					{name: 'street',checkType: 'notnull',errorMsg: '请选择完整的省市区街道信息'},
					{name: 'introduce',checkType: 'notnull',errorMsg: '请输入自我介绍'},
					{name: 'idcard_front',checkType: 'notnull',errorMsg: '请上传身份证正面照'},
					{name: 'idcard_back',checkType: 'notnull',errorMsg: '请上传身份证反面照'},
					{name: 'certification',checkType: 'notnull',errorMsg: '请上传其他相关证明文件照片（如：驾照，健康证，护理证等）'},
					{name: 'health_image',checkType: 'notnull',errorMsg: '请上传健康证'},
				];
				//进行表单检查
				delete formData.state
				delete formData.city_name
				delete formData.applytime
				let checkRes = graceChecker.check(formData, rule);
				// ..检查是否注册-没注册跳转注册
				if (checkRes) {
					uni.request({
						url: '/Userapply/apply',
						method: 'POST',
						data: formData,
						success: res => {
							// 提示
							console.log(res, res.res.code)
							if (res.res.code == 30001) {
								this.$wanlshop.to('/pages/user/setting/verified')
							} else {
								this.getInfo({
									t: this.formData.type
								})
								// this.$wanlshop.msg('提交成功');
								uni.redirectTo({
									url:`/pages/page/success?type=apply&order_type=${this.formData.type}`
								})
							}
						}
					});
				} else {
					this.$wanlshop.msg(graceChecker.error);
				}
			},
			close(index,item) {
			    this[item].splice(index,1);
			},
			// 选择图片
			chooseImg(name) {
				if (this.formData.state === 0 || this.formData.state === 1) {
					this.previewImage([this.$wanlshop.oss(this.formData[name])], 0)
					return false;
				}
				uni.chooseImage({
					sourceType: ["camera", "album"],
					sizeType: "compressed",
					count: 1,
					success: res => {
						// 上传图片
						uni.request({
							url: '/wanlshop/common/uploadData',
							success: updata => {
								uni.uploadFile({
									url: updata.data.uploadurl,
									filePath: res.tempFilePaths[0],
									name: 'file',
									formData: updata.data.storage == 'local' ? null :
										updata.data.multipart,
									success: res => {
										if (name == 'certification') {
											this.certification.push(JSON.parse(res.data).data.fullurl)
										} else if(name == 'health_image') {
											this.health_image.push(JSON.parse(res.data).data.fullurl)
										} else {
											this.formData[name] = JSON.parse(res.data)
												.data.fullurl
										}
									},
									fail: error => {
										this.$wanlshop.msg(JSON.parse(error.data).msg);
									}
								});
							}
						});
					}
				})
			},
			//预览图片
			previewImage(urls, key) {
				uni.previewImage({
					urls: urls,
					current: urls[key],
					indicator: 'number'
				});
			},

			treeConfirm(e) {
				const idKeysResult = e.map((x)=>{
					return x.id
				})
				const nameKeysResult = e.map((x)=>{
					return x.name
				})
				if(nameKeysResult.length > 0) {
					this.homekeep_text = nameKeysResult.join(',');
				}
				if(idKeysResult.length > 0) {
					this.formData.homekeep_ids = idKeysResult.join(',');
				}
				this.homekeep_ids = idKeysResult
			},
			showTree() {
				// if (this.formData.state === 0 || this.formData.state === 1) {
				// 	return false
				// }
				//打开选择器
				const options = JSON.parse(JSON.stringify(this.serves))
				const newOptions = this.deepCheckValue(options, this.homekeep_ids, 'id', 'item')
				this.serves = [...newOptions]
				this.$refs.gqTree._show();
				//关闭选择器
				//this.$refs.gqTree._hide();
			},
			findItemById(arrs,ids) {
				arrs.map((item, index) => {
					if (ids.indexOf(item.id) > -1) { //此处判断num大于0再进行操作
						this.temp.push(item.name);
					}
					if (item.item && item.item.length > 0) { //有子集的话 继续调用
						this.findItemById(item.item, ids);
					}
				});
				return this.temp;
			},
			deepCheckValue(options, values, idKey, childKey) {
				return options.map((i) => {
					if (values.indexOf(i[idKey]) > -1) {
						i['isGqAddChecked'] = true
					} else {
						i['isGqAddChecked'] = false
					}
					if (i[childKey] && i[childKey].length > 0) {
						this.deepCheckValue(i[childKey], values, idKey, childKey)
					}
					return i
				})
			}
		}
	}
</script>

<style lang="less">
	.cu-form-group {
		padding: 0;
		view {
			&.right {
				max-width: 480rpx;
			}
		}
		.title {
			min-width: calc(4em + 15px);

			text {
				&:nth-child(1) {
					display: inline-block;
					width: 40rpx;
				}

				&:last-child {
					color: #333333;
					font-size: 28rpx;
					font-weight: normal;
				}
			}
		}

		input {
			text-align: right;
			font-size: 28rpx;
			color: #333333;
		}

		.list {
			width: 100%;
			padding: 0 40rpx 38rpx 40rpx;

			.item {
				width: 286rpx;
				height: 226rpx;
				background-color: #EDEDED;
				border-radius: 6rpx;
				margin-right: 38rpx;
				position: relative;
				.rightLeftImg {
					width: 286rpx;
					height: 226rpx;
				}
				.cu-tag {
					position: absolute;
					top: 0;
					right: 0;
					border-bottom-left-radius: 3px;
					padding: 3px 6px;
					height: auto;
					background-color: rgba(0, 0, 0, 0.5);
				}
				&:nth-child(2n) {
					margin-right: 0;
				}

				image {
					width: 206rpx;
					height: 103rpx;
				}
			}
		}
	}

	.iconfont {
		color: #777777;
		font-size: 40rpx;
	}

	.switch-sex {
		transform: scale(0.8);
	}

	.textarea {
		width: 100%;
		height: 180rpx;

		textarea {
			width: 100%;
			height: 100%;
			margin: 0;
			padding: 10rpx;
		}
	}

	.tips {
		background-color: rgba(255, 0, 0, 0.1);
		padding: 10rpx 0;
		text-align: center;
		color: #f00;
		font-size: 26rpx;

		&.color1 {
			background-color: rgba(76, 189, 102, 0.1);
			color: #4CBD66;
		}
	}
	.cu-form-group.area{
		position: relative;
	}
	.cu-form-group.area .click{
		position: absolute;
		z-index: 99;
		right: 0;
		left: 0;
		top: 0;
		bottom: 0;
	}
	
	.xieyi {
		display: flex;
		margin-top: 20rpx;
		font-size: 24rpx;
	}
	
	.xieyi_content {
		line-height: 60rpx;
		margin-left: 20rpx;
	}
	
	.xieyi text {
		color: red;
		margin-left: 10rpx;
	}
</style>